package jdktcp.client;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class JDKTcpClientForConnectionReset {

    static int timeout = 1000 * 10;

    static String host = "localhost";
    static int port = 9999;

    public JDKTcpClientForConnectionReset() {

        try (Socket client = new Socket()) {

            client.setSoTimeout(timeout);
            client.setSoLinger(true, 0);
            client.connect(new InetSocketAddress(host, port), timeout);
            System.out.println("start connect to:" + host + ":" + port);

            sendAndRevice(client);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendAndRevice(Socket client) throws Exception {
        System.out.println("connect:" + client);
        OutputStream out = client.getOutputStream();
        out.write(("HelloServer").getBytes());
        System.out.println("request first ok");


        //获取输入流，接收服务端的响应数据
        InputStream in = client.getInputStream();

        //从流中读取字节
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        while (true) {
            int oneByte = in.read(); //read处于阻塞状态,等待客户端全部发送完成,此时如果server端强制关闭socket会触发connection reset
            //System.out.println("read [" + i + "] byte:" + oneByte);
            if (oneByte == -1) {
                break;
            }
            outputStream.write(oneByte);
        }
        byte[] buff = outputStream.toByteArray();
        System.out.println("response data==>" + new String(buff));
    }


    private static void test(Socket client, OutputStream out, InputStream in) throws Exception {
        for (int i = 0; i < 3000; i++) {
            TimeUnit.MILLISECONDS.sleep(100);

            byte[] buff = new byte[1024];
            client.getInputStream().read(buff);
            System.out.println("response last==>" + new String(buff).trim());

        }
    }

    public static void main(String[] args) throws Exception {
        new JDKTcpClientForConnectionReset();
    }
}
